<template>
	
	<view v-if="bgCoverImg" class="content" :style="{'background-image': `url(${bgCoverImg})`}">
		
		<view v-if="!isHaveLoad" class="loding" >
			
			<input class="input1" type="text" value=""  @input="loding" placeholder="输入用户名" data-type='yhm' />
			<input class="input1" type="text" password="true" @confirm="lodbut" value="" placeholder="输入密码" @input="loding"  data-type='mm' />
			<view class="lodbut"  @click="lodbut">登录</view>
		</view>
		<view   v-if="isHaveLoad" @tap="toCoinSkin()" class="coin" :class="{'coin-spin':isStatusText === '币定','coin-facade': isStatusText === '正面','coin-reverse': isStatusText === '反面'}">
			<view class="coin-front">
				<image class="coin-img" :src="coinImgFront"></image>
			</view>
			<view class="coin-middle" v-for="index in 16" :key="index" :style="'transform: translateZ(' + index + 'px)'">
				<image class="coin-img coin-img-filp" :src="coinImgBack"></image>
			</view>
			<view class="coin-back">
				<image class="coin-img coin-img-filp" :src="coinImgBack"></image>
			</view>
			<view class="coin-shadow"></view>
		</view>
		<view  v-if="isHaveLoad" class="coin-record">
			<view class="coin-result">{{record.result}}</view>
			<view class="coin-record-text">抛掷总次数：{{record.totalCount}}</view>
			<view class="coin-record-text">正面次数：{{record.facadeCount}}, 占比：{{record.facadeProportion}}</view>
			<view class="coin-record-text">反面次数：{{record.reverseCount}}, 占比：{{record.reverseProportion}}</view>
		</view>
		<button  v-if="isHaveLoad" class="footer-btn" @tap="tossCoin()">抛硬币</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				coinImgFront: '',
				coinImgBack: '',
				isStatusText: '币定',
				bgCoverImg: '',
				record: {},
				username:'',
				mm:'',
				isHaveLoad:0
			}
		}, 
 
	
		onLoad() {
			uni.hideTabBar(); //隐藏tab

			uni.showShareMenu({
				withShareTicket: true
			})
			uni.showModal({
				title: '',
				content: '出现困惑了吗？不妨试试掷硬币吧。',
				showCancel: false,
				confirmText: '开始',
				confirmColor: '#fd746c',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		onShow() {
			this.getBgImg();
			this.getCoinImg();
			this.getCoinRecord();
			// #ifndef MP-ALIPAY
			this.getAudio();
			// #endif
			this.record.result = '币定';
			this.isStatusText = '币定';
		},
		methods: {
			
			loding: function(event) {
			    
				console.log(event)
				console.log(event.currentTarget.dataset.type)
				console.log(event.detail.value)
				var value = event.detail.value
				if(event.currentTarget.dataset.type=='yhm')
				{
					this.username = event.target.value
				}
				if(event.currentTarget.dataset.type=='mm')
				{
					this.mm = event.target.value
				}
				console.log("data是",this.$data)
				
			},
			// 获取背景图
			lodbut:function(event){
				console.log("点击登录")
				var a = this.$data.username
				var b = this.$data.mm
				console.log(a,'变量a')
				// 获取db引用
				const db = uniCloud.database() //代码块为cdb
				// 使用uni-clientDB
				db.collection('user')
				   .where({
					   username:a
				   })
				    .get()
				  .then((res)=>{
				    // res 为数据库查询结果
					console.log('查询成功',res)
					if(res.result.data.length){
						console.log("查有人")
						console.log("密码是",res.result.data[0].mm)
						if(b==res.result.data[0].mm){
							console.log("登录成功")
							this.$data.isHaveLoad=1
								console.log(this.$data)
							uni.showTabBar(); //显示tab
							
						}
						else{
							
									uni.showModal({
										title: '',
										content: '登录失败，请核对密码',
										showCancel: false,
										confirmText: '好的',
										confirmColor: '#fd746c',
										success: function(res) {
											if (res.confirm) {
												console.log('用户点击确定');
											} else if (res.cancel) {
												console.log('用户点击取消');
											}
										}
									});
						}
					}
					else{
						uni.showModal({
							title: '',
							content: '登录失败，请核对用户名',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#fd746c',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				  }).catch((err)=>{
					  
					  		
				    console.log('查询错误',err.code); // 打印错误码
				        console.log(err.message); // 打印错误内容
				  })
				
				
				
				
				// if (this.$data.username=='lizhenyong'){
				// 	if(this.$data.mm=='lizhenyong'){
				// 		console.log("登录成功")
				// 		this.$data.isHaveLoad=1
				// 		console.log(this.$data)
				// 		uni.showTabBar(); //显示tab


				// 	}
					
				// }
				// else{
				// 	console.log("登录失败")
				// 		uni.showModal({
				// 			title: '',
				// 			content: '登录失败，请核对密码',
				// 			showCancel: false,
				// 			confirmText: '好的',
				// 			confirmColor: '#fd746c',
				// 			success: function(res) {
				// 				if (res.confirm) {
				// 					console.log('用户点击确定');
				// 				} else if (res.cancel) {
				// 					console.log('用户点击取消');
				// 				}
				// 			}
				// 		});
				// }
				
				
			},
			
			
			getBgImg() {
				let bgSrc = uni.getStorageSync('bgCoverImg') || 'bg_4';
				this.bgCoverImg = `https://746f-tosscoin-whstu-1259588940.tcb.qcloud.la/img/${bgSrc}.jpg`;
				this.bgCoverImg = `https://tosscoin-1256354221.file.myqcloud.com/img/${bgSrc}.jpg`;
			},
			// 获取硬币图片
			getCoinImg() {
				let name = uni.getStorageSync('coinName') || '2020shu'
				this.coinImgFront = `https://tosscoin-1256354221.file.myqcloud.com/img/${name}_front.png`
				this.coinImgBack = `https://tosscoin-1256354221.file.myqcloud.com/img/${name}_back.png`
				
			},
			// 获取硬币旋转音频
			getAudio() {
				let name = uni.getStorageSync('coinAuidoID') || 'filpCoin1';
				this.audioSrc = name === 'wu' ? null : `/static/audio/${name}.mp3`;
				
			},
			// 获取硬币记录
			getCoinRecord() {
				let result = this.isStatusText;
				let facadeCount = uni.getStorageSync('recordFacadeCount') || 0;
				let reverseCount = uni.getStorageSync('recordReverseCount') || 0;
				let totalCount = facadeCount + reverseCount;
				let facadeProportion = totalCount <= 0 ? "0%" : (Math.round(facadeCount / totalCount * 10000) / 100.00) + "%";
				let reverseProportion = totalCount <= 0 ? "0%" : (Math.round(reverseCount / totalCount * 10000) / 100.00) + "%";
				this.record = {
					result: result,
					totalCount: totalCount,
					facadeCount: facadeCount,
					reverseCount: reverseCount,
					facadeProportion: facadeProportion,
					reverseProportion: reverseProportion
				}
				// 彩蛋1号
				if (totalCount === 10) {
					uni.showModal({
						title: '',
						content: '最好的都是即将发生的',
						showCancel: false,
						confirmText: '喜欢你',
						confirmColor: '#fd746c',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/pages/easteregg/easteregg'
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			// 前往2048小游戏
			toCoinSkin() {
				
				uni.switchTab({
					url:'./index1'
				})
			},
			// 抛硬币
			tossCoin() {
				// #ifndef MP-ALIPAY
				if (this.audioSrc) {
					this.loadAudio()
				} else {
					this.filpCoin();
				}
				// #endif
				// #ifdef MP-ALIPAY
				this.filpCoin();
				// #endif 
			},
			// 加载音频
			loadAudio() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = this.audioSrc;
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
					this.filpCoin();
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
					this.filpCoin();
				});
			},
			// 翻转硬币
			filpCoin() {
				this.record.result = '旋转中...';
				this.isStatusText = '旋转';
				this.timerCoinFilp = setTimeout(() => {					
					let flipResult = Math.random();
					if (flipResult < 0.5) {
						this.isStatusText = '正面';
						let facadeCount = this.record.facadeCount + 1
						uni.setStorageSync('recordFacadeCount', facadeCount);
					} else {
						this.isStatusText = '反面';
						let reverseCount = this.record.reverseCount + 1
						uni.setStorageSync('recordReverseCount', reverseCount);
					}
					this.timerCoinRecord = setTimeout(() => {
						this.getCoinRecord();
					}, 1000);
				}, 0);
			},
			// 清除定时器 
			clearTimerCoinFilp() {
				clearTimeout(this.timerCoinFilp);
				this.timerCoinFilp = null;
				console.log('timerCoinFilp', this.timerCoinFilp)
			},
			clearTimerCoinRecord() {
				clearTimeout(this.timerCoinRecord);
				this.timerCoinRecord = null;
				console.log('timerCoinRecord', this.timerCoinRecord)
			}
		},
		onHide: function() {
			this.timerCoinFilp && this.clearTimerCoinFilp();
			this.timerCoinRecord && this.clearTimerCoinRecord();
		}
	}
</script>

<style lang="scss">
	.input1{
		width: 500rpx;
		height: 80rpx;
		
		margin-top: 40rpx;
		background-color: #FFFFFF;
		padding: 5rpx;
		display: flex;
		justify-content: center;
	}
	.loding{
		width: 100vw;
		height: 100vh;
		background-color: blue($color: #eeeee0);
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		position: fixed;
		z-index: 2;
		top: 0;
		
		
	}
	.lodbut{
		width: 500rpx;
		height: 100rpx;
		background-color: #FFFFFF;
		display: flex;
		justify-content: center;
		margin-top: 200rpx;
		align-items: center;
	}
	.content {
		width: 100%;
		height: 100vh;
		box-sizing: border-box;
		background-color: #f8f8f8;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-attachment: fixed;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	$coin-diameter: 200px; //直径
	$coin-thickness: 16px; // 厚度
	$turn-time: 1s; // 转动时间

	/* 3d旋转 */
	.coin {
		position: relative;
		width: $coin-diameter;
		height: $coin-diameter;
		margin: 0 auto;
		transform-style: preserve-3d;
	}

	.coin-spin {
		animation: flipSpin 6s linear infinite;
	}

	.coin-facade {
		animation: flipFacade $turn-time ease-out forwards;
	}

	.coin-reverse {
		animation: flipReverse $turn-time ease-out forwards;
	}

	.coin-front,
	.coin-back {
		position: absolute;
		width: $coin-diameter;
		height: $coin-diameter;
		border-radius: 50%;
		overflow: hidden;
		mask-image: radial-gradient(white, black); // 解决因 animation 导致 border-radius 失效的问题

		&:after {
			content: "";
			position: absolute;
			left: -$coin-diameter/2;
			bottom: 100%;
			display: block;
			height: $coin-diameter/1.5;
			width: $coin-diameter*2;
			background: #fff;
			opacity: 0.3;
			animation: shine linear 3s infinite;
		}
	}

	.coin-front {
		transform: translateZ(17px);
	}

	.coin-back {
		transform: translateZ(0);
	}

	.coin-img-filp {
		transform: rotateY(180deg);
	}

	.coin-middle {
		width: $coin-diameter;
		height: $coin-diameter;
		transform: translateZ(1px);
		position: absolute;
	}

	.coin-img {
		width: $coin-diameter;
		height: $coin-diameter;
	}

	.coin-shadow {
		position: absolute;
		width: $coin-diameter;
		height: $coin-thickness;
		border-radius: 50%;
		background: #000;
		box-shadow: 0 0 $coin-thickness*5 $coin-thickness*5 #000;
		opacity: 0.125;
		transform: rotateX(90deg) translateZ(-$coin-diameter*1.1) scale(.5);
	}

	.coin-result {
		font-size: 18pt;
		margin-top: 80rpx;
		margin-bottom: 20rpx;
		color: #e64340;
	}

	.coin-record {
		text-align: center;
		color: #FFFFFF;
		margin-bottom: 60rpx;
		font-size: 14pt;
	}


	.coin-record-text {
		margin-bottom: 10rpx;
	}

	@keyframes flipSpin {
		0% {
			transform: perspective(1000px) rotateY(0deg);
		}

		100% {
			transform: perspective(1000px) rotateY(360deg);
		}
	}

	@keyframes flipFacade {
		from {
			transform: perspective(1000px) rotateY(0);
		}

		to {
			transform: perspective(1000px) rotateY(1800deg);
		}
	}

	@keyframes flipReverse {
		from {
			transform: perspective(1000px) rotateY(0);
		}

		to {
			transform: perspective(1000px) rotateY(1980deg);
		}
	}

	@keyframes shine {

		0%,
		15% {
			transform: translateY($coin-diameter*2) rotate(-40deg);
		}

		50% {
			transform: translateY(-$coin-diameter) rotate(-40deg);
		}
	}
</style>
